import React, {useCallback, useEffect, useState} from 'react';
import MarkdownIt from 'markdown-it';
import {withRouter} from 'react-router-dom'
import MdEditor from 'react-markdown-editor-lite';
import {
    Button,
    Input,
    Drawer,
    message
} from 'antd';
import SearchTag from "../Article/SearchTag";


import 'react-markdown-editor-lite/lib/index.css';
import './index.css';
import axiosConfig from "../../utils/axios.config";
import axios from "axios";


const {TextArea} = Input
const ArticleEditor = (props) => {


    const {history} = props
    //本次页面的动作,依据不同的动作做相应的事情
    const [behave,setBeHave] = useState('');
    // 编辑时输入的值
    const [value, setValue] = useState("");
    // 抽屉的隐藏与显示
    const [visible, setVisible] = useState(false);
    // 文章标题的显示
    const [title,setTitle] = useState('');
    //文章的id
    const [articleId,setArticleId] = useState('')
    // 输入文章的简介
    const [abstract,setAbstract] = useState('');

    //标签
    const [tags,setTags] = useState([])


    // markdown-it 利用设置参数，具体查询markdown-it官网
    const mdParser = new MarkdownIt({
        html: true,
        linkify: false,
        typographer: true
    }).enable('image');



    // 检测markdown数据变化
    function handleEditorChange({text}) {
        setValue(text)
    }

    
    // 初始化，组件渲染完成时调用，获取浏览器的地址参数，明确当前需要做的动作
    const initBehave=useCallback(()=>{
        const param = history.location.search.split('?behave=')[1];
        if(param.includes('editArticle')){
            const [,id,title] = [...decodeURIComponent(param).split('/')];
            getOneArticle(id,title)
            setBeHave( 'editArticle')
        }else if(param ==='createArticle'){
            setBeHave( 'createArticle')
        }
    },[])

    const getOneArticle = useCallback((id,title)=>{
        axios({
            url:'/blog/article/getArticle',
            baseURL:axiosConfig.baseAddress,
            params:{
                id,
                title
            }
        }).then(response=>{
            const data = response.data
            console.log(data)
            setTitle(data.title)
            setTags(data.articleTags)
            console.log(data.articleTags)
            setValue(data.body)
            setAbstract(data.abstract)
            setArticleId(data.id)
        }).catch((err)=>{
            console.log(err)
        })
    },[])

    function handleOneArticle(){
        console.log(articleId)
        const url = behave==='createArticle'?'/article/createArticle':'/article/editorArticle'
        const key = 'handleOneArticle'
        const data = {
            id:articleId+'',
            title,
            abstract,
            tags,
            body:value
        }
        message.loading({content:'发布中...',key})
        axios({
            url,
            baseURL:axiosConfig.baseURL,
            method:'POST',
            data
        }).then(response=>{
            console.log(response.data)
            if(response.data.code==1){
                message.success({content:'发布成功',key})
            }else {
                message.warn({content:'发布失败',key})
            }
        }).catch(err=>{
            message.warn({content:'发布失败',key})
            console.log(err)
        })
    }

    useEffect(()=>{
       initBehave();
    },[])


    return (

        <div className='article-editor-card'>
            <header className='article-editor-header'>
                <Input onChange={(e)=>{setTitle(e.target.value)}} value={title}  placeholder={'输入文章标题...'} size='large'/>
                <div className='article-editor-header-btn'>
                    <Button type={"primary"} size={"large"}>存入草稿</Button>
                    <Button type={"primary"} onClick={()=>{setVisible(true)}} size={"large"}>完成</Button>
                </div>
            </header>
            <MdEditor
                value={value}
                onChange={handleEditorChange}
                renderHTML={text => mdParser.render(text)}
                style={
                    {
                        height: '100%',
                    }
                }
            >
            </MdEditor>
            {/*抽屉*/}
            <Drawer title="发布文章" placement="right" onClose={()=>{setVisible(false)}} visible={visible}>
                <ul>
                    <li>
                        <span>选择标签:</span>&nbsp;<SearchTag defaultValue={tags} setTags={setTags} />
                    </li>
                    <li>
                        <span>输入摘要:</span>
                        <TextArea
                            showCount style={{
                            height:'200px'
                            }}
                            maxLength={200}
                            onChange={(e)=>{
                                setAbstract(e.target.value)
                            }}
                            value={abstract}
                        />
                    </li>
                    <Button 
                        style={{
                            marginTop:'15px',
                            marginLeft:'calc(100% - 80px)'
                        }} 
                        type={'primary'} 
                        onClick={()=>{
                            handleOneArticle()
                        }}
                    >确定发布</Button>
                </ul>

            </Drawer>
        </div>

    );
};

export default withRouter(ArticleEditor);